import 'package:aero_frisbee/app/model/af_home_user_model/af_home_user_model.dart';
import 'package:aero_frisbee/app/model/local_post_model/local_post_model.dart';
import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/home/view_model/af_home_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/followed/view_model/af_followed_list_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import 'views/af_more_action_sheet.dart';
import 'views/af_report_options_sheet.dart';
import 'views/profile_detail_post_cell.dart';

class AfProfileDetailScreen extends ConsumerStatefulWidget {
  const AfProfileDetailScreen({super.key, required this.item});
  final LocalPostModel item;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfProfileDetailScreenState();
}

class _AfProfileDetailScreenState extends ConsumerState<AfProfileDetailScreen> {
  AfHomeUserModel? get homeUser => widget.item.cacheBind?.homeUser; // homeUser
  @override
  Widget build(BuildContext context) {
    final userInfo = ref
        .watch(getUserInfoFutureProvider(
            userId: widget.item.cacheBind?.homeUser?.userId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );

    ref.listen(unfriendServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getUserInfoFutureProvider);
      }
    });
    ref.listen(unblockServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getUserInfoFutureProvider);
      }
    });

    ref.listen(reportServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "Report Success".toast();
      }
    });

    final homePost = ref.watch(afHomePostListServiceProvider);
    final homeList = homePost.maybeWhen(
      orElse: () => List<LocalPostModel>.from([]),
      data: (data) => data,
    );
    final retList = homeList
        .where(
          (element) => element.author == widget.item.author,
        )
        .toList();
    return Scaffold(
      backgroundColor: const Color(0xffffffff),
      appBar: AppBar(
          leadingWidth: 40,
          leading: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(left: 16, right: 0, bottom: 3),
              child: Assets.icons.iconBack.image(),
            ),
          ),
          actions: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                showAfMoreActionSheet(
                  context,
                  isFriend: userInfo?.isFriend == true,
                  isBlock: userInfo?.isBlock == true,
                  onFollowClick: () {
                    if (userInfo?.isFriend == true) {
                      ref
                          .read(unfriendServiceProvider.notifier)
                          .unfriend(userId: userInfo?.userId ?? '');
                    } else {
                      ref
                          .read(addFriendServiceProvider.notifier)
                          .addFriend(userId: userInfo?.userId ?? '');
                    }
                  },
                  onBlackClick: () {
                    if (userInfo?.isBlock == true) {
                      ref
                          .read(unblockServiceProvider.notifier)
                          .unblock(broadcasterId: userInfo?.userId ?? '');
                    } else {
                      ref
                          .read(blockServiceProvider.notifier)
                          .block(broadcasterId: userInfo?.userId ?? '');
                    }
                  },
                  onReportClick: () {
                    showAfReportOptionsSheet(
                      context,
                      onReportClick: (report) {
                        ref.read(reportServiceProvider.notifier).report(
                            complainSub: report,
                            userId: userInfo?.userId ?? '');
                      },
                    );
                  },
                );
              },
              child: Padding(
                padding: const EdgeInsets.only(
                    right: 20, left: 0, top: 5, bottom: 5),
                child: Assets.icons.iconMore.image(width: 28),
              ),
            ),
          ]),
      extendBodyBehindAppBar: true,
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: Stack(
          children: [
            AspectRatio(
              aspectRatio: 1125 / 564,
              child: Assets.images.mine.profileBg.image(),
            ),
            Column(
              children: [
                SizedBox(
                  height: MediaQuery.of(context).padding.top,
                ),
                const SizedBox(
                  height: kToolbarHeight,
                ),
              ],
            ),
            Column(
              children: [
                AspectRatio(
                  aspectRatio: 1125 / 345,
                  child: Container(
                    decoration: const BoxDecoration(),
                  ),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Expanded(
                      flex: 82,
                      child: SizedBox(
                        height: 20,
                      ),
                    ),
                    Expanded(
                      flex: 88,
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: FractionallySizedBox(
                          widthFactor: 1,
                          heightFactor: 1,
                          child: Stack(
                            children: [
                              Container(
                                decoration: const BoxDecoration(),
                                padding: const EdgeInsets.all(12),
                                child: LayoutBuilder(
                                  builder: (BuildContext context,
                                      BoxConstraints constraints) {
                                    return ClipRRect(
                                      borderRadius: BorderRadius.circular(
                                          constraints.maxHeight / 2),
                                      child: AspectRatio(
                                        aspectRatio: 1,
                                        child: CachedNetworkImage(
                                          imageUrl: homeUser?.avatar ?? '',
                                          fit: BoxFit.fill,
                                          placeholder: (context, url) =>
                                              const Material(
                                            color: Color(0xffF2F5F9),
                                            child: Center(
                                              child: SizedBox(
                                                width: 25,
                                                height: 25,
                                                child:
                                                    CircularProgressIndicator(
                                                  strokeWidth: 2,
                                                  color: Color(0xffADADAD),
                                                  backgroundColor: Colors.white,
                                                ),
                                              ),
                                            ),
                                          ),
                                          errorWidget: (context, url, error) =>
                                              const CircularProgressIndicator(
                                            strokeWidth: 2,
                                            color: Color(0xffADADAD),
                                            backgroundColor: Colors.white,
                                          ),
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ),
                              Positioned(
                                bottom: 13,
                                right: 13,
                                child: Visibility(
                                  visible: userInfo?.isFriend != true,
                                  child: GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      ref
                                          .read(
                                              addFriendServiceProvider.notifier)
                                          .addFriend(
                                              userId: userInfo?.userId ?? '');
                                    },
                                    child: Container(
                                      decoration: const BoxDecoration(),
                                      child: Padding(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 2,
                                          vertical: 0,
                                        ),
                                        child: Assets.icons.iconProfileFollowBtn
                                            .image(width: 26),
                                      ),
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 205,
                      child: Column(
                        children: [
                          const SizedBox(
                            height: 65,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const SizedBox(
                                width: 70,
                              ),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Expanded(
                                          child: Text(
                                            homeUser?.nickname ?? '',
                                            style: const TextStyle(
                                              color: Color(0xff202020),
                                              fontWeight: FontWeight.w500,
                                              fontSize: 18,
                                            ),
                                            textAlign: TextAlign.left,
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 5,
                                          ),
                                        ),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                      ],
                                    ),
                                    const SizedBox(
                                      height: 10,
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 20,
                              ),
                            ],
                          )
                        ],
                      ),
                    )
                  ],
                ),
                const SizedBox(
                  height: 20,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                          color: const Color(0xffEEEEEE),
                          width: 1,
                        ),
                      ),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 40, vertical: 4),
                      child: Assets.icons.iconProfileGiftBtn.image(width: 22),
                    ),
                    const SizedBox(
                      width: 20,
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        AFLogPvManger.stat(page: AFLogPages.tabChat);
                        context.pushNamed(RouteUri.messageDetai,
                            queryParams: {"userId": homeUser?.userId ?? ''});
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(20),
                          gradient: const LinearGradient(
                            colors: [
                              Color(0xff0CEBEB),
                              Color(0xff29FFC6),
                            ],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                          ),
                        ),
                        padding: const EdgeInsets.symmetric(
                            horizontal: 20, vertical: 4),
                        child: Row(
                          children: [
                            Assets.icons.iconProfileChatBtn.image(width: 22),
                            const SizedBox(
                              width: 10,
                            ),
                            const Text(
                              'Chat',
                              style: TextStyle(
                                color: Color(0xffffffff),
                                fontWeight: FontWeight.normal,
                                fontSize: 18,
                              ),
                              textAlign: TextAlign.center,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            )
                          ],
                        ),
                      ),
                    )
                  ],
                ),
                const SizedBox(
                  height: 20,
                ),
                const Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: 20),
                    child: Text(
                      'Gift',
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ),
                Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                  child: Assets.images.mine.profileGiftsBg.image(),
                ),
                const SizedBox(
                  height: 10,
                ),
                const Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(left: 20),
                    child: Text(
                      'post',
                      style: TextStyle(
                        color: Color(0xff000000),
                        fontWeight: FontWeight.w500,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ),
                GridView.custom(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
                  scrollDirection: Axis.vertical,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, //横轴三个子widget
                      mainAxisSpacing: 10,
                      crossAxisSpacing: 10,
                      childAspectRatio: 162 / 233 //宽高比为1时，子widget
                      ),
                  childrenDelegate: SliverChildBuilderDelegate(
                    (context, position) {
                      return ProfileDetailPostCell(
                        retList[position],
                      );
                    },
                    childCount: retList.length,
                  ),
                ),
                // Container(
                //   decoration: BoxDecoration(
                //     color: const Color(0xffF3FFE2),
                //     borderRadius: BorderRadius.circular(16),
                //   ),
                //   margin:
                //       const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                //   padding:
                //       const EdgeInsets.symmetric(horizontal: 0, vertical: 6),
                //   child: const Row(
                //     children: [
                //       SizedBox(
                //         width: 10,
                //       ),
                //       Expanded(
                //         child: GiftMineCell(
                //           type: 0,
                //         ),
                //       ),
                //       Expanded(
                //         child: GiftMineCell(
                //           type: 0,
                //         ),
                //       ),
                //       Expanded(
                //         child: GiftMineCell(
                //           type: 0,
                //         ),
                //       ),
                //       SizedBox(
                //         width: 10,
                //       ),
                //     ],
                //   ),
                // ),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfProfileDetailScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class GiftMineCell extends StatelessWidget {
  const GiftMineCell({Key? key, this.type = 0}) : super(key: key);

  final int type;

  Widget get image {
    switch (type) {
      case 0:
        return Assets.icons.iconGiftsLeft.image();
      case 1:
        return Assets.icons.iconGiftsMid.image();
      default:
        return Assets.icons.iconGiftsRight.image();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: AspectRatio(
            aspectRatio: 1,
            child: image,
          ),
        ),
        const Align(
          alignment: Alignment.center,
          child: Text(
            '0',
            style: TextStyle(
              color: Color(0xff6B770B),
              fontWeight: FontWeight.normal,
              fontSize: 18,
            ),
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        )
      ],
    );
  }
}
